<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          :readonly="!!dataForm.id"
          v-model="dataForm.userName"
          placeholder="登录用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <!-- :class="{ 'is-required': !dataForm.id }" -->
        <el-input
          v-model="dataForm.nickName"
          type="nickName"
          placeholder="昵称"
        ></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="avatarUrl">
        <div class="avatar-upload">
          <input type="file" id="btn_file" style="display:none">
          <img @click="uploadAvatar" v-show="!dataForm.avatarUrl" class="avatar-upload-img" src="~@/assets/img/add.png" />
          <img v-show="dataForm.avatarUrl" class="avatar-upload-img" :src="dataForm.avatarUrl" />
        </div>
        <el-input
          v-model="dataForm.avatarUrl"
          type="avatarUrl"
          class="avatar-text"
          placeholder="头像"
        ></el-input>
      </el-form-item>
      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          class="width100"
          style="width:100%"
          type="date"
          placeholder="生日"
          v-model="dataForm.birthday"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="dataForm.sex">
          <el-radio
            v-for="item in dataForm.sexList"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="手机号"></el-input>
      </el-form-item>
      <el-form-item label="角色" size="mini" prop="roleIds">
        <el-checkbox-group v-model="dataForm.roleIds">
          <el-checkbox
            v-for="role in roleList"
            :key="role.id"
            :label="role.id"
            >{{ role.name }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio
            v-for="item in dataForm.statusList"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
import { GetUserByIdApi, SaveUserApi } from "@/api/user";
import { GetRoleDropDownApi } from "@/api/role";
export default {
  data() {
    var validateEmail = (rule, value, callback) => {
      if (value) {
        if (!isEmail(value)) {
          callback(new Error("邮箱格式错误"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        userName: "",
        nickName: "",
        avatarUrl: "",
        birthday: "",
        sex: 1,
        sexList: [{ label: "男", value: 1 }, { label: "女", value: 2 }],
        email: "",
        phone: "",
        roleIds: [],
        status: 1,
        statusList: [{ label: "正常", value: 1 }, { label: "停用", value: 2 }]
      },
      dataRule: {
        userName: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        // password: [{ validator: validatePassword, trigger: "blur" }],
        // comfirmPassword: [
        //   { validator: validateComfirmPassword, trigger: "blur" }
        // ],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        roleIds: [{ required: true, message: "必须选择角色", trigger: "blur" }]
      }
    };
  },
  methods: {
    init(id, isAdd) {
      GetRoleDropDownApi()
        .then(res => {
          this.roleList = res.data.data;
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          if (!isAdd) {
            GetUserByIdApi(id)
              .then(res => {
                this.dataForm.id = res.data.data.id;
                this.dataForm.userName = res.data.data.userName;
                this.dataForm.status = res.data.data.status;
                this.dataForm.nickName = res.data.data.userInfo.nickName;
                this.dataForm.avatarUrl = res.data.data.userInfo.avatarUrl;
                this.dataForm.birthday = res.data.data.userInfo.birthday;
                this.dataForm.sex = res.data.data.userInfo.sex;
                this.dataForm.email = res.data.data.userInfo.email;
                this.dataForm.phone = res.data.data.userInfo.phone;
                this.dataForm.roleIds = res.data.data.userRole.map(t => {
                  return t.id;
                });
              })
              .catch(err => {
                window.console.log(err);
              });
          } else {
            this.dataForm.id = null;
            this.dataForm.userName = null;
            this.dataForm.status = 1;
            this.dataForm.nickName = null;
            this.dataForm.avatarUrl = null;
            this.dataForm.birthday = null;
            this.dataForm.sex = 1;
            this.dataForm.email = null;
            this.dataForm.phone = null;
            this.dataForm.roleIds = [];
          }
        })
        .catch(err => {
          window.console.log(err);
        });
    },
    uploadAvatar(){
      document.getElementById("btn_file").click(); 
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          SaveUserApi(this.dataForm)
            .then(res => {
              if (res.data.code == 200) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch(err => {
              window.console.log(err);
              this.$message.error(err.message);
            });
          return;
        }
      });
    }
  }
};
</script>
<style lang="scss">
.avatar-text {
  display: none;
}
.avatar-upload {
  width: 62px;
  height: 60px;
  border-radius: 10px;
  background-color: rgb(233, 233, 233);
  .avatar-upload-img {
    width: 50px;
    height: 50px;
    margin: 5px;
  }
}
.avatar-upload:hover {
  background-color: rgb(201, 201, 201);
  cursor: pointer;
}
</style>
